package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ArticleCollectionService;
import com.heima.common.constant.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.thread.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ArticleCollectionServiceImpl implements ArticleCollectionService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        Integer userId = UserThreadLocalUtil.getUser();
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }


        String collectionJson = (String)cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + dto.getEntryId().toString(), userId.toString());
        if(StringUtils.isNotBlank(collectionJson) && dto.getOperation() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章已收藏");
        }
        if (dto.getOperation() == 0){
            //收藏文章
            log.info("【收藏文章】key:{} {} {}", BehaviorConstants.COLLECTION_BEHAVIOR, dto.getEntryId(), userId);
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + dto.getEntryId().toString(), userId.toString(), JSON.toJSONString(dto));
        }else if(dto.getOperation() == 1){
            //取消收藏
            log.info("【取消收藏】key:{} {}", BehaviorConstants.COLLECTION_BEHAVIOR, dto.getEntryId(), userId);
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + dto.getEntryId().toString(), userId.toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}